package com.py.framework.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.framework.common.Constants;
import com.py.framework.common.controller.SystemController;
import com.py.framework.core.common.Page;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.entity.LogEntity;
import com.py.framework.service.SysLogService;
import com.py.framework.utils.DateUtil;

/**
 * 系统日志Controller
 * @author Leegern
 * @date   2018年4月23日
 */
@RestController
@RequestMapping("/syslog")
public class SysLogController extends SystemController {
	
	@Autowired
	private SysLogService sysLogService;
	
	/**
	 * @api {post} /syslog/addLogInfo.json 添加系统日志
	 * @apiName addLogInfo
	 * @apiVersion 0.0.1
	 * @apiGroup 系统日志管理 
	 * @apiParam {LogEntity} entity 系统日志实体
	 * @apiParam {String}  username 用户名
	 * @apiParam {String}  realName 真实姓名
	 * @apiParam {String}  requestIp 请求IP
	 * @apiParam {String}  requestUrl 请求资源URL
	 * @apiParam {String}  shortRequestUrl 请求资源URL(去除根路径) 
	 * @apiParam {String}  requestContent 请求内容
	 * @apiParam {int}  logType 日志类型：1：系统日志，2：登录日志
	 * @apiParamExample {json} 请求参数示例
	 *  {"username":"zhangsan","realName":"张三","requestIp":"10.0.0.1","requestUrl":"/syslog/addLogInfo.json","shortRequestUrl":"/syslog/addLogInfo.json","logType":1,"requestContent":"params=222"}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/addLogInfo", method = RequestMethod.POST)
	public RestServiceResult<Object> addLogInfo(@RequestBody LogEntity entity) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				sysLogService.sendToQueue(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("添加失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {get} /syslog/queryLogForPage.json 分页查询系统日志列表
	 * @apiName queryLogForPage
	 * @apiVersion 0.0.1
	 * @apiGroup 系统日志管理 
	 * @apiParam {int}  page 当前页码
	 * @apiParam {int}  limit 每页条数
	 * @apiParam {String}  realName 真实姓名
	 * @apiParam {String}  sysName 系统名称
	 * @apiParam {int}  logType 日志类型：1：系统日志，2：登录日志
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} username 用户名
	 * @apiSuccess {String} realName 真实姓名
	 * @apiSuccess {String} requestIp 请求IP
	 * @apiSuccess {String} requestUrl 请求资源URL
	 * @apiSuccess {String} shortRequestUrl 请求资源URL(去除根路径) 
	 * @apiSuccess {String} requestContent 请求内容
	 * @apiSuccess {int}  logType 日志类型：1：系统日志，2：登录日志
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":10,"data":[{"username":"zhangsan","realName":"张三","requestIp":"10.0.0.1","requestUrl":"/syslog/addLogInfo.json","shortRequestUrl":"/syslog/addLogInfo.json","logType":1,"requestContent":"params=222"}]}
	 */
	@RequestMapping(value = "/queryLogForPage", method = RequestMethod.POST)
	public RestServiceResult<List<LogEntity>> queryLogForPage(int page, int limit, String realName, String sysName, 
			@RequestParam(value="logType",required=false,defaultValue="0")int logType) {
		Map<String, Object> params = new HashMap<>();
		Page pager = super.getPage(page, limit);
		params.put("page", pager);
		params.put("realName", realName);
		params.put("sysName",  sysName);
		params.put("logType",  logType);
		List<LogEntity> datas = sysLogService.queryLogForPage(params);
		return super.getPageSuccessRestServiceResult(pager.getTotalCount(), datas);
	}
	
	@RequestMapping(value = "/export", method = RequestMethod.GET)
	public RestServiceResult<List<LogEntity>> export(String realName,HttpServletResponse response, 
			@RequestParam(value="logType",required=false,defaultValue="0")int logType) {
		List<LogEntity> datas = sysLogService.queryLog(realName,logType);
		List<String> showColumns = new ArrayList<String>();
		
		showColumns.add("用户名");
		showColumns.add("真实姓名");
		
		showColumns.add("操作描述");
		showColumns.add("操作时间");
		try {
			downloadExcel(response, datas, "操作日志", "操作日志详情", showColumns);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.getSuccessRestServiceResult(datas);
	}
	
	/**
	 * @api {post} /syslog/findOneLog.json 根据日志Id查询日志信息
	 * @apiName findOneLog
	 * @apiVersion 0.0.1
	 * @apiGroup 系统日志管理 
	 * @apiParam {long}  id 日志Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} username 用户名
	 * @apiSuccess {String} realName 真实姓名
	 * @apiSuccess {String} requestIp 请求IP
	 * @apiSuccess {String} requestUrl 请求资源URL
	 * @apiSuccess {String} shortRequestUrl 请求资源URL(去除根路径) 
	 * @apiSuccess {String} requestContent 请求内容
	 * @apiSuccess {int}  logType 日志类型：1：系统日志，2：登录日志
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":{"username":"zhangsan","realName":"张三","requestIp":"10.0.0.1","requestUrl":"/syslog/addLogInfo.json","shortRequestUrl":"/syslog/addLogInfo.json","logType":1,"requestContent":"params=222"}}
	 */
	@RequestMapping(value = "/findOneLog", method = RequestMethod.POST)
	public RestServiceResult<LogEntity> findOneLog(long id) {
		LogEntity data = null;
		if (id > Constants.NUMBER_ZERO) {
			data = sysLogService.findOneLog(id);
		}
		return super.getSuccessRestServiceResult(data);
	}
	
	public void downloadExcel(HttpServletResponse response, List<LogEntity> datas, String fileNanme, String sheetName, List<String> showColumns) throws Exception {
		response.setContentType("application/vnd.ms-excel");
		HSSFWorkbook workbook = null;
		OutputStream fOut = null;
		// 进行转码，使其支持中文文件名
		fileNanme = URLEncoder.encode(fileNanme, "UTF-8");
		response.setHeader("content-disposition", "attachment;filename=" + fileNanme + ".xls");
		// 产生工作簿对象
		workbook = new HSSFWorkbook();
		// 产生工作表对象
		HSSFSheet sheet = workbook.createSheet();
		workbook.setSheetName(0, sheetName);
		HSSFRow row = null;
		HSSFCell cell = null;
	

		// 创建标题行
		row = sheet.createRow(0);
		for (int i = 0; i < showColumns.size(); i++) {
			cell = row.createCell(i);
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(showColumns.get(i));
		}
		for (int i = 0; i < datas.size(); i++) {
			row = sheet.createRow(i + 1);// 创建一行			
				
				
				cell = row.createCell(0);// 创建一列
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(datas.get(i).getUsername());
				
				cell = row.createCell(1);// 创建一列
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(datas.get(i).getRealName());
				
				
				
				cell = row.createCell(2);// 创建一列
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(datas.get(i).getRequestDesc());
				
				cell = row.createCell(3);// 创建一列
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(DateUtil.getInstance().parseDateStr(datas.get(i).getCreateTime().toString(), "yyyy-MM-dd"));

				} 

		

		fOut = response.getOutputStream();
		workbook.write(fOut);
		workbook.close();
		fOut.flush();
		fOut.close();
	}
}